module fiona_common_mod

  use container
  use flogger
  use string
#ifdef HAS_MPI
  use mpi
#endif
  use netcdf

  implicit none

  integer, parameter :: max_ndim = 7

contains

  pure integer function round_robin(m, n, i) result(j)

    integer, intent(in) :: m
    integer, intent(in) :: n
    integer, intent(in) :: i

    integer d, r

    if (m >= n) then
      d = m / n
      r = m - d * n
      j = i / d
      if (i >= d * (n - r)) then
        j = (i - (m - r * (d + 1))) / (d + 1) + n - r
      end if
    else
      j = i
    end if

  end function round_robin

  subroutine handle_error(ierr, msg, file, line)

    integer, intent(in) :: ierr
    character(*), intent(in) :: msg
    character(*), intent(in), optional :: file
    integer, intent(in), optional :: line

    if (ierr /= NF90_NOERR) then
      call log_error(trim(msg) // ' ' // trim(NF90_STRERROR(ierr)) // ' CODE ' // trim(to_str(ierr)), file, line)
    end if

  end subroutine handle_error

end module fiona_common_mod
